package com.dataart.productshop.somepackageforspringstopfuckmybrain;

import com.dataart.productshop.Constants;
import com.dataart.productshop.controller.MainController;
import com.dataart.productshop.file.UploadFileItem;
import com.dataart.productshop.file.utils.FileValidate;
import com.dataart.productshop.file.utils.StringUtils;
import com.dataart.productshop.model.FileInfo;
import com.dataart.productshop.service.FileInfoManager;
import com.dataart.productshop.service.PictureManager;
import com.dataart.productshop.service.TypeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

@Controller
@RequestMapping("/upload")
public class UploadController {

	private static final Logger logger = LoggerFactory.getLogger(MainController.class);
	public static String START_UPLOAD_PAGE = "upload";
	public static String ITEM_NAME = "uploadItem";
	public static String TYPES = "types";
	
	@Value(Constants.PROP_FILE_PATH)
	private String filePath;
	
	@Autowired
	private FileInfoManager fileInfoManager;
	
	@Autowired
	private PictureManager pictureManager;
	
	@Autowired
	private TypeManager typeManager;
	
	@RequestMapping(method = RequestMethod.GET)
	public String getUploadForm(Model model) {
		model.addAttribute(ITEM_NAME, new UploadFileItem());
		model.addAttribute(TYPES, typeManager.getAll());
		return START_UPLOAD_PAGE;
	}

	@RequestMapping(method = RequestMethod.POST)
	public String create(@ModelAttribute("uploadItem")UploadFileItem uploadItem,
			Model model) {

		CommonsMultipartFile uploadMultiFile = uploadItem.getFileData();
		//validate 
		if(uploadItem.isValidateFile() && !validateItem(uploadItem, model)){
			model.addAttribute(ITEM_NAME, uploadItem);
			model.addAttribute(TYPES, typeManager.getAll());
			return START_UPLOAD_PAGE;
		}
		
		//createFoldername + the folder
		String folderName = StringUtils.nextNextFolderPath(filePath);
		//create full path to folder: starting from src/...
		String itemFolderPath = filePath + "/" + folderName;
		//filePath
		String itemFilePath = itemFolderPath + "/" + uploadMultiFile.getOriginalFilename();
		File transferZipFile = new File(itemFilePath);

		//save MainFile
		try {
			transferZipFile.createNewFile();
			uploadMultiFile.transferTo(transferZipFile);
		} catch (IOException e) {
            StringUtils.rollbackFolderCreation(itemFolderPath);
            logger.error(e.getMessage());
			return START_UPLOAD_PAGE;
		}
		//saving fileInfo in base
		FileInfo fileInfo = createFileInfo(uploadItem, folderName + "/" + uploadMultiFile.getOriginalFilename());
		//saving pictures in filesystem and base
		if (!pictureManager.savePictures(itemFolderPath, fileInfo, uploadItem.getPictureFiles())){
			logger.error("can't save picture files");
		}

		return "redirect:/";
	}
	
	public boolean validateItem(UploadFileItem item, Model model){
		//validate item
		boolean result = true;
		if(!isValide(item)){
			result =  false;
		}
		try{
			Long.parseLong(item.getType());
		} catch(NumberFormatException ex){
			result = false;
		}
		//validate zip
		if(!FileValidate.validateZip(item.getFileData())){
			model.addAttribute("validateZipMessage", true);
			item.setFileData(null);
			result = false;
		}
		
		//validate pictures
		MultipartFile[] pictFiles = item.getPictureFiles();
		
		for (int i = 0; i < pictFiles.length; i++) {
			if(pictFiles[i] == null || pictFiles[i].isEmpty()){
				continue;
			} else {
				if(!FileValidate.validatePicture(pictFiles[i])){
					model.addAttribute("validatePictureMessage" + (i + 1),true);
					item.getPictureFiles()[i] = null;
					result = false;
				}
			}
		}
		return result;
	}
	/**
	 * create and save in database fileInfo object, it's desirable to call the method after 
	 * file save in filesystem
	 * 
	 * @param item the wrap-object of fileItem
	 * @param path to file( without prefix ${store.path} : see above)
	 * @return fileInfo which saved in database
	 */
	private FileInfo createFileInfo(UploadFileItem item, String path){
		FileInfo createdFile = new FileInfo();
		
		createdFile.setName(item.getName());
		createdFile.setDescription(item.getDescription());
		createdFile.setFilePath(path);
		createdFile.setType(typeManager.getById(Long.parseLong(item.getType())));
		createdFile.setCreatedDate(new Date());
		createdFile.setDownloads(0L);
		//TODO: check on get another name
		//TODO: auto-create of data and downloads
		fileInfoManager.saveFileInfo(createdFile);
		
		return createdFile;
	}
	
	private boolean isValide(UploadFileItem item){
		return !item.getName().isEmpty() && !item.getDescription().isEmpty()
				&& item.getFileData() != null && !item.getType().isEmpty();
	}

}
